#include "flightnumber.h"

using namespace aviation;

// Constructors

FlightNumber::FlightNumber()
{
	m_c1 = 'A';
	m_c2 = 'A';
	m_number = 111;
}
		
FlightNumber::FlightNumber(const std::string& flightString)
{
	// We allow strings that are too long but not too short.
	if(flightString.length() < 5) throw std::exception("Attempted to instantiate a FlightNumber object with a string that is too short.");

	char c1 = flightString[0];
	char c2 = flightString[1];

	int lowercaseOffset = 32;

	//Check that the characters are uppercase 
	if(!(c1 >= 'A' && c1 <= 'Z')) 
	{
		c1 -= lowercaseOffset;
		if(!(c1 >= 'A' && c1 <= 'Z')) 
			throw std::exception("Attempted to instantiate a FlightNumber with a string that has a first character that is not a letter.");
	}

	if(!(c2 >= 'A' && c2 <= 'Z')) 
	{
		c2 -= lowercaseOffset;
		if(!(c2 >= 'A' && c2 <= 'Z')) 
			throw std::exception("Attempted to instantiate a FlightNumber with a string that has a second character that is not a letter.");
	}

	char n1 = flightString[2];
	char n2 = flightString[3];
	char n3 = flightString[4];

	//Check that the integers are all between 0 and 9
	if(!(n1 >= '0' && n1 <= '9')) throw std::exception("Attempted to instantiate a FlightNumber with a string that has a third character that is not a number.");
	if(!(n2 >= '0' && n2 <= '9')) throw std::exception("Attempted to instantiate a FlightNumber with a string that has a fourth character that is not a number.");
	if(!(n3 >= '0' && n3 <= '9')) throw std::exception("Attempted to instantiate a FlightNumber with a string that has a fifth character that is not a number.");

	m_c1 = c1;
	m_c2 = c2;

	const int asciiOffset = 48;

	m_number = (n1-asciiOffset) * 100 + (n2-asciiOffset) * 10 + (n3 - asciiOffset);
}

FlightNumber::~FlightNumber()
{
}

FlightNumber::FlightNumber(const FlightNumber& other)
{
	*this = other;
}

// Operators

FlightNumber& FlightNumber::operator=(const FlightNumber& other)
{
	m_c1 = other.m_c1;
	m_c2 = other.m_c2;
	m_number = other.m_number;

	return *this;
}

const bool FlightNumber::operator==(const FlightNumber& other) const
{
	return m_c1 == other.m_c1 && m_c2 == other.m_c2 && m_number == other.m_number;
}

const bool FlightNumber::operator!=(const FlightNumber& other) const
{
	return !(*this == other);
}

// Accessors

const std::string FlightNumber::AsString() const
{
	std::string tmp;

	tmp += m_c1;
	tmp += m_c2;
	tmp += util::XtoA(m_number, 3, '0');

	// returns flight number as a string
	return tmp;
}